package com.idcheck.rechadfire;

import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.ContactsContract;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutCompat;
import android.util.Log;
import android.view.Surface;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.exoplayer2.ExoPlaybackException;
import com.google.android.exoplayer2.ExoPlayer;
import com.google.android.exoplayer2.ExoPlayerFactory;
import com.google.android.exoplayer2.Format;
import com.google.android.exoplayer2.PlaybackParameters;
import com.google.android.exoplayer2.Player;
import com.google.android.exoplayer2.SimpleExoPlayer;
import com.google.android.exoplayer2.Timeline;
import com.google.android.exoplayer2.decoder.DecoderCounters;
import com.google.android.exoplayer2.extractor.DefaultExtractorsFactory;
import com.google.android.exoplayer2.extractor.ExtractorsFactory;
import com.google.android.exoplayer2.source.ExtractorMediaSource;
import com.google.android.exoplayer2.source.LoopingMediaSource;
import com.google.android.exoplayer2.source.MediaSource;
import com.google.android.exoplayer2.source.TrackGroupArray;
import com.google.android.exoplayer2.source.hls.HlsMediaSource;
import com.google.android.exoplayer2.trackselection.AdaptiveTrackSelection;
import com.google.android.exoplayer2.trackselection.DefaultTrackSelector;
import com.google.android.exoplayer2.trackselection.TrackSelection;
import com.google.android.exoplayer2.trackselection.TrackSelectionArray;
import com.google.android.exoplayer2.trackselection.TrackSelector;
import com.google.android.exoplayer2.ui.AspectRatioFrameLayout;
import com.google.android.exoplayer2.ui.PlayerView;
import com.google.android.exoplayer2.ui.SimpleExoPlayerView;
import com.google.android.exoplayer2.upstream.DataSource;
import com.google.android.exoplayer2.upstream.DefaultBandwidthMeter;
import com.google.android.exoplayer2.upstream.DefaultDataSourceFactory;
import com.google.android.exoplayer2.util.Util;
import com.google.android.exoplayer2.video.VideoRendererEventListener;
import com.idcheck.utils.AppPermission;
import com.idcheck.utils.FileUtil;
import com.idcheck.utils.LogUtil;
import com.idcheck.utils.MediaFileUtil;
import com.idcheck.utils.OtherUtil;
import com.tencent.bugly.crashreport.CrashReport;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;


import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONObject;


/*
Created by: Ayal Fieldust
Date: 8/2017

Description:
This Example app was created to show a simple example of ExoPlayer Version 2.8.4.
There is an option to play mp4 files or live stream content.
Exoplayer provides options to play many different formats, so the code can easily be tweaked to play the requested format.
Scroll down to "ADJUST HERE:" I & II to change between sources.
Keep in mind that m3u8 files might be stale and you would need new sources.
 */

public class FullscreenActivity extends AppCompatActivity implements VideoRendererEventListener {


    private static final String TAG = "ADFire";
    private PlayerView simpleExoPlayerView;
    private SimpleExoPlayer player;
    List<String> videolist;
    List<String> cmd1list;
    List<String> cmd2list;
    List<String> cmd3list;
    List<String> playlist;
    private int current = 0;
    static TcpServerThread tcpServerTread;
    private CountDownTimer mTimer=null; //UI业务倒计时
    private volatile long TimeStamp = -1L;
    private ImageView playImage;
    private int ImageTime = 15;
    private int CmdTime = 3600;
    private int isCmd = 0;
    private String rootPath;
    private String currentFile;

    private static int tick_recv = 0;
    private static int tick_send = 0;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_fullscreen);
        videolist = new ArrayList<>();
        cmd1list = new ArrayList<>();
        cmd2list = new ArrayList<>();
        cmd3list = new ArrayList<>();
        playImage = (ImageView) this.findViewById(R.id.player_image);

        CrashReport.initCrashReport(getApplicationContext(), "33d54e97d8", false);
        //eventbus
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }


        if(getSupportActionBar()!=null){

            getSupportActionBar().hide();

        }

        tcpServerTread= new TcpServerThread(6000);
        tcpServerTread.start();

        if (AppPermission.isGrantExternalRW(this)) {

        }

        excute();

        /*new RxPermissions(this)
                .request(Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .subscribe(granted -> {
                    if (granted) {
                        Log.e("黑蜂运动", "所有权限都已打开！");
                        excute();
                    } else {
                        Log.e("黑蜂运动", "至少有一个权限被禁止！");
                        excute();
                    }
                });*/

//        Uri mp4VideoUri = Uri.parse(videolist.get(current));
//        DefaultBandwidthMeter bandwidthMeter = new DefaultBandwidthMeter(); //test
//
//        TrackSelection.Factory videoTrackSelectionFactory = new AdaptiveTrackSelection.Factory(bandwidthMeter);
//        TrackSelector trackSelector =
//                new DefaultTrackSelector(videoTrackSelectionFactory);
//
//        // 2. Create the player
//        player = ExoPlayerFactory.newSimpleInstance(this, trackSelector);
//        simpleExoPlayerView = new SimpleExoPlayerView(this);
//        simpleExoPlayerView = (SimpleExoPlayerView) findViewById(R.id.player_view);
//
//        int h = simpleExoPlayerView.getResources().getConfiguration().screenHeightDp;
//        int w = simpleExoPlayerView.getResources().getConfiguration().screenWidthDp;
//        Log.v(TAG, "height : " + h + " weight: " + w);
//        ////Set media controller
//        simpleExoPlayerView.setUseController(false);//set to true or false to see controllers
//        simpleExoPlayerView.requestFocus();
//        // Bind the player to the view.
//        simpleExoPlayerView.setPlayer(player);
//
//        // Measures bandwidth during playback. Can be null if not required.
//        // Produces DataSource instances through which media data is loaded.
//        DataSource.Factory dataSourceFactory = new DefaultDataSourceFactory(this, Util.getUserAgent(this, "exoplayer2example"), bandwidthMeter);
//        // This is the MediaSource representing the media to be played.
////        MediaSource videoSource = new ExtractorMediaSource.Factory(dataSourceFactory).createMediaSource(liveStreamUri);
//
//        //// II. ADJUST HERE:
//
//        ////        DefaultDataSourceFactory dataSourceFactory = new DefaultDataSourceFactory(this, Util.getUserAgent(this, "exoplayer2example"), bandwidthMeterA);
//        ////Produces Extractor instances for parsing the media data.
//        //        ExtractorsFactory extractorsFactory = new DefaultExtractorsFactory();
//
//        //This is the MediaSource representing the media to be played:
//        //FOR SD CARD SOURCE:
//        //        MediaSource videoSource = new ExtractorMediaSource(mp4VideoUri, dataSourceFactory, extractorsFactory, null, null);
//
//        //FOR LIVESTREAM LINK:
//        ExtractorsFactory extractorsFactory = new DefaultExtractorsFactory();
//        MediaSource videoSource = new ExtractorMediaSource(mp4VideoUri, dataSourceFactory, extractorsFactory, null, null);
//        //MediaSource videoSource = new HlsMediaSource(mp4VideoUri, dataSourceFactory, 1, null, null);
//        final LoopingMediaSource loopingSource = new LoopingMediaSource(videoSource);
//        // Prepare the player with the source.
//        player.prepare(videoSource);
//        player.addListener(new ExoPlayer.EventListener() {
//
//
//            @Override
//            public void onTimelineChanged(Timeline timeline, Object manifest, int reason) {
//
//            }
//
//            @Override
//            public void onTracksChanged(TrackGroupArray trackGroups, TrackSelectionArray trackSelections) {
//                Log.v(TAG, "Listener-onTracksChanged... ");
//            }
//
//            @Override
//            public void onLoadingChanged(boolean isLoading) {
//
//            }
//
//            @Override
//            public void onPlayerStateChanged(boolean playWhenReady, int playbackState) {
//                Log.v(TAG, "Listener-onPlayerStateChanged..." + playbackState+"|||isDrawingCacheEnabled():"+simpleExoPlayerView.isDrawingCacheEnabled());
//                switch(playbackState){
//                    case Player.STATE_ENDED:
//                        PlayNext();
//                        break;
//                    default:
//                        // status = PlaybackStatus.IDLE;
//                        break;
//                }
//            }
//
//            @Override
//            public void onRepeatModeChanged(int repeatMode) {
//
//            }
//
//            @Override
//            public void onShuffleModeEnabledChanged(boolean shuffleModeEnabled) {
//
//            }
//
//            @Override
//            public void onPlayerError(ExoPlaybackException error) {
//                Log.v(TAG, "Listener-onPlayerError...");
////                player.stop();
////                player.prepare(loopingSource);
////                player.setPlayWhenReady(true);
//                PlayNext();
//            }
//
//            @Override
//            public void onPositionDiscontinuity(int reason) {
//
//            }
//
//            @Override
//            public void onPlaybackParametersChanged(PlaybackParameters playbackParameters) {
//
//            }
//
//            @Override
//            public void onSeekProcessed() {
//
//            }
//        });
//        player.setPlayWhenReady(true); //run file/link when ready to play.
//        player.setVideoDebugListener(this);
    }

    private void excute() {
        loadFile();
        initTimer();

        playCurrent();
    }

    @Override
    public void onVideoEnabled(DecoderCounters counters) {

    }

    @Override
    public void onVideoDecoderInitialized(String decoderName, long initializedTimestampMs, long initializationDurationMs) {

    }

    @Override
    public void onVideoInputFormatChanged(Format format) {

    }

    @Override
    public void onDroppedFrames(int count, long elapsedMs) {

    }

    @Override
    public void onVideoSizeChanged(int width, int height, int unappliedRotationDegrees, float pixelWidthHeightRatio) {
        Log.v(TAG, "onVideoSizeChanged [" + " width: " + width + " height: " + height + "]");

    }

    @Override
    public void onRenderedFirstFrame(Surface surface) {

    }

    @Override
    public void onVideoDisabled(DecoderCounters counters) {

    }
//-------------------------------------------------------ANDROID LIFECYCLE---------------------------------------------------------------------------------------------

    @Override
    protected void onStop() {
        super.onStop();
        Log.v(TAG, "onStop()...");
    }

    @Override
    protected void onStart() {
        super.onStart();
        Log.v(TAG, "onStart()...");
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.v(TAG, "onResume()...");
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.v(TAG, "onPause()...");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.v(TAG, "onDestroy()...");
        EventBus.getDefault().unregister(this);
        if(null != player)
        player.release();
        unInitTimer();
        //CommUtil.shutDownServerSocket();
    }
    private void initTimer(){
        if (mTimer == null) {
            mTimer = new CountDownTimer((long) (99999999 * 1000), 1000) {

                @Override
                public void onTick(long millisUntilFinished) {

                    if (!FullscreenActivity.this.isFinishing()) {
                        Log.e(TAG, "======"+String.valueOf(TimeStamp)+"=====");
                        if(TimeStamp == -1){
                            ;
                        }
                        else if(TimeStamp == 0){

                            TimeStamp = -1;
                            EventMessageForReset();

                            PlayNext();

                        }else{
                            TimeStamp--;
                        }
//                          for ping
                        long totalMilliSeconds = System.currentTimeMillis();
                        long totalSeconds = totalMilliSeconds / 1000;

                        //求出现在的秒
                        Log.d("ping",String.valueOf(totalSeconds));
                        if(((totalSeconds % 3 ) == 0)){
                            EventMessageForPing();
                        }


                    }
                }

                @Override
                public void onFinish() {
                    Log.e("zpan", "======onFinish=====");
                }
            };
            mTimer.start();
        }
    }
    private void unInitTimer(){
        if (mTimer != null) {
            mTimer.cancel();
            mTimer = null;
        }
    }

    private void playImage(String currentFile, int current){
        try {
            findViewById(R.id.player_image).setLayoutParams(new LinearLayout.LayoutParams(LinearLayoutCompat.LayoutParams.MATCH_PARENT, LinearLayoutCompat.LayoutParams.MATCH_PARENT, 0));
            Bitmap bmpDefaultPic;
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inSampleSize = 2;//图片的压缩比率，越大，压缩的越厉害
            bmpDefaultPic = BitmapFactory.decodeFile(currentFile, options);
            playImage.setImageBitmap(bmpDefaultPic);
        }
        catch(Exception e){

        }
        if(isCmd == 2)
        {
            if (current == 0) {
                TimeStamp = 60;
            } else {
                TimeStamp = 5;
            }
        }else{
            TimeStamp = 15;
        }


    }
    private void playVideo(String currentFile){
        findViewById(R.id.player_image).setLayoutParams(new LinearLayout.LayoutParams(LinearLayoutCompat.LayoutParams.MATCH_PARENT, LinearLayoutCompat.LayoutParams.MATCH_PARENT, 1));
        if(player != null){
            player.release();
            player = null;
        }

        Uri mp4VideoUri = Uri.parse(currentFile);
        DefaultBandwidthMeter bandwidthMeter = new DefaultBandwidthMeter(); //test

        TrackSelection.Factory videoTrackSelectionFactory = new AdaptiveTrackSelection.Factory(bandwidthMeter);
        TrackSelector trackSelector =
                new DefaultTrackSelector(videoTrackSelectionFactory);

        // 2. Create the player
        player = ExoPlayerFactory.newSimpleInstance(this, trackSelector);
        simpleExoPlayerView = new SimpleExoPlayerView(this);
        simpleExoPlayerView = (SimpleExoPlayerView) findViewById(R.id.player_view);

        int h = simpleExoPlayerView.getResources().getConfiguration().screenHeightDp;
        int w = simpleExoPlayerView.getResources().getConfiguration().screenWidthDp;
        Log.v(TAG, "height : " + h + " weight: " + w);
        ////Set media controller
        simpleExoPlayerView.setUseController(false);//set to true or false to see controllers
        simpleExoPlayerView.requestFocus();
        // Bind the player to the view.
        simpleExoPlayerView.setPlayer(player);

        // Measures bandwidth during playback. Can be null if not required.
        // Produces DataSource instances through which media data is loaded.
        DataSource.Factory dataSourceFactory = new DefaultDataSourceFactory(this, Util.getUserAgent(this, "exoplayer2example"), bandwidthMeter);
        // This is the MediaSource representing the media to be played.
//        MediaSource videoSource = new ExtractorMediaSource.Factory(dataSourceFactory).createMediaSource(liveStreamUri);

        //// II. ADJUST HERE:

        ////        DefaultDataSourceFactory dataSourceFactory = new DefaultDataSourceFactory(this, Util.getUserAgent(this, "exoplayer2example"), bandwidthMeterA);
        ////Produces Extractor instances for parsing the media data.
        //        ExtractorsFactory extractorsFactory = new DefaultExtractorsFactory();

        //This is the MediaSource representing the media to be played:
        //FOR SD CARD SOURCE:
        //        MediaSource videoSource = new ExtractorMediaSource(mp4VideoUri, dataSourceFactory, extractorsFactory, null, null);

        //FOR LIVESTREAM LINK:
        ExtractorsFactory extractorsFactory = new DefaultExtractorsFactory();
        MediaSource videoSource = new ExtractorMediaSource(mp4VideoUri, dataSourceFactory, extractorsFactory, null, null);
        //MediaSource videoSource = new HlsMediaSource(mp4VideoUri, dataSourceFactory, 1, null, null);
        final LoopingMediaSource loopingSource = new LoopingMediaSource(videoSource);
        // Prepare the player with the source.
        player.prepare(videoSource);
        player.addListener(new ExoPlayer.EventListener() {


            @Override
            public void onTimelineChanged(Timeline timeline, Object manifest, int reason) {

            }

            @Override
            public void onTracksChanged(TrackGroupArray trackGroups, TrackSelectionArray trackSelections) {
                Log.v(TAG, "Listener-onTracksChanged... ");
            }

            @Override
            public void onLoadingChanged(boolean isLoading) {

            }

            @Override
            public void onPlayerStateChanged(boolean playWhenReady, int playbackState) {
                Log.v(TAG, "Listener-onPlayerStateChanged..." + playbackState+"|||isDrawingCacheEnabled():"+simpleExoPlayerView.isDrawingCacheEnabled());
                switch(playbackState){
                    case Player.STATE_ENDED:
                        if(player != null){
                            player.release();
                            player = null;
                        }
                        PlayNext();
                        break;
                    default:
                        // status = PlaybackStatus.IDLE;
                        break;
                }
            }

            @Override
            public void onRepeatModeChanged(int repeatMode) {

            }

            @Override
            public void onShuffleModeEnabledChanged(boolean shuffleModeEnabled) {

            }

            @Override
            public void onPlayerError(ExoPlaybackException error) {
                Log.v(TAG, "Listener-onPlayerError...");
                player.stop();
                player.prepare(loopingSource);
                player.setPlayWhenReady(true);
            }

            @Override
            public void onPositionDiscontinuity(int reason) {

            }

            @Override
            public void onPlaybackParametersChanged(PlaybackParameters playbackParameters) {

            }

            @Override
            public void onSeekProcessed() {

            }
        });
        player.setPlayWhenReady(true); //run file/link when ready to play.
        player.setVideoDebugListener(this);
    }
    private boolean loadFile()
    {
        //hasRemovable();
        loadStorage();
        loadCmd1File();
        loadCmd2File();
        //sortFile();
        playlist = videolist;
        if(playlist.size() == 0){
            AlertDialog alertDialog1 = new AlertDialog.Builder(this)
                    .setTitle("提示")//标题
                    .setMessage("请根据说明书添加播放文件")//内容
                    .setIcon(R.mipmap.ic_launcher)//图标
                    .create();
            alertDialog1.show();
        }
        return true;
    }
//    private boolean sortFile(){
//
//    }

//    private Boolean hasRemovable(){
//        File[] files = ContextCompat.getExternalFilesDirs(this,null);
//        for(int i=0;i<files.length;i++){
//            Toast.makeText(FullscreenActivity.this,files[i].getPath(),Toast.LENGTH_LONG);
//            new AlertDialog.Builder(this)
//                    .setTitle(String.valueOf(i))
//                    .setMessage(files[i].getPath()+files[i].getName())
//                    .show();
//        }
//
//        return true;
//    }

    private Boolean loadStorage(){
        boolean sdCardExist = Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
        if(sdCardExist == false){
            return false;
        }
        createWorkDir();
        //获得SD卡根目录路径
        rootPath =Environment.getExternalStorageDirectory().getAbsolutePath();
        String sdpath = rootPath+File.separator+"adfire"+File.separator+"ad"+File.separator;
        //LogUtil.getInstance().info("错误日志+++++=====" + sdpath);
        //Toast.makeText(FullscreenActivity.this, sdpath, Toast.LENGTH_LONG).show();
        File workDir = new File(sdpath);
        FileUtil.scanFileList(workDir,videolist);
        videolist = orderByName(sdpath);
        return true;
    }
    private Boolean loadCmd1File(){
        boolean sdCardExist = Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
        if(sdCardExist == false){
            return false;
        }
        createWorkDir();
        //获得SD卡根目录路径
        rootPath =Environment.getExternalStorageDirectory().getAbsolutePath();
        String sdpath = rootPath+File.separator+"adfire"+File.separator+"cmd1"+File.separator;
        //Toast.makeText(FullscreenActivity.this, sdpath, Toast.LENGTH_LONG).show();
        File workDir = new File(sdpath);
        FileUtil.scanFileList(workDir,cmd1list);
        cmd1list = orderByName(sdpath);
        //Toast.makeText(FullscreenActivity.this, "获取的cmd1文件数：" + cmd1list.size(), Toast.LENGTH_LONG).show();
        return true;
    }
    private Boolean loadCmd2File(){
        boolean sdCardExist = Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
        if(sdCardExist == false){
            return false;
        }
        createWorkDir();
        //获得SD卡根目录路径
        rootPath =Environment.getExternalStorageDirectory().getAbsolutePath();
        String sdpath = rootPath+File.separator+"adfire"+File.separator+"cmd2"+File.separator;
        File workDir = new File(sdpath);
        FileUtil.scanFileList(workDir,cmd2list);
        cmd2list = orderByName(sdpath);
        return true;
    }
    private Boolean loadCmd3File(){
        boolean sdCardExist = Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
        if(sdCardExist == false){
            return false;
        }
        createWorkDir();
        //获得SD卡根目录路径
        rootPath =Environment.getExternalStorageDirectory().getAbsolutePath();
        String sdpath = rootPath+File.separator+"adfire"+File.separator+"cmd3"+File.separator;
        File workDir = new File(sdpath);
        FileUtil.scanFileList(workDir,cmd3list);
        cmd3list = orderByName(sdpath);
        return true;
    }
    public ArrayList<String> orderByName(String filePath) {
        ArrayList<String> FileNameList = new ArrayList<String>();
        File file = new File(filePath);
        File[] files = file.listFiles();
        List fileList = Arrays.asList(files);
        Collections.sort(fileList, new Comparator<File>() {
            @Override
            public int compare(File o1, File o2) {
                if (o1.isDirectory() && o2.isFile())
                    return -1;
                if (o1.isFile() && o2.isDirectory())
                    return 1;
                return o1.getName().compareTo(o2.getName());
            }
        });
        for (File file1 : files) {
            if (!file1.isDirectory()) {
                FileNameList.add(file1.getAbsolutePath());
            }
        }
        return FileNameList;
    }

    private void EventMessageForReply(){
        try{
            tcpServerTread.sendData("{\"cmd\":\"confirm\"}");
        }
        catch (Exception e){

        }
    }
    private void EventMessageFor1(){
        try{
            isCmd = 1;
            if(MediaFileUtil.isVideoFileType(currentFile)){
                player.stop();
            }
            playlist = cmd1list;
            current = 0;
            playCurrent();

//            String cmdfile ;
//            String rootPath =Environment.getExternalStorageDirectory().getAbsolutePath();
//            String sdpath = rootPath+File.separator+"adfire"+File.separator+"cmd"+File.separator;
//            File vcmdFile = new File(sdpath );
//
//            if(vcmdFile.exists()){
//
//                File [] files = vcmdFile.listFiles();
//                for(int i=0;i<files.length;i++){
//                    Log.d(TAG, files[i].getName());
//                    if(files[i].getName().indexOf('1') > -1){
//                        currentFile = files[i].getAbsolutePath();
//                        break;
//                    }
//                }
//                if(MediaFileUtil.isVideoFileType(currentFile)){
//                    TimeStamp = -1;
//                    playVideo(currentFile);;
//                }else{
//                    findViewById(R.id.player_image).setLayoutParams(new LinearLayout.LayoutParams(LinearLayoutCompat.LayoutParams.MATCH_PARENT, LinearLayoutCompat.LayoutParams.MATCH_PARENT, 0));
//                    Bitmap bmpDefaultPic;
//
//
//                    bmpDefaultPic = BitmapFactory.decodeFile(currentFile,null);
//                    playImage.setImageBitmap(bmpDefaultPic);
//                    TimeStamp = CmdTime;
//                    isCmd = true;
//                }
//            }
        }
        catch (Exception e){

        }

    }
    private void EventMessageFor2(){
        try{
            isCmd = 2;
            if(MediaFileUtil.isVideoFileType(currentFile)){
                player.stop();
            }
            playlist = cmd2list;
            current = 0;
            playCurrent();

//            String rootPath =Environment.getExternalStorageDirectory().getAbsolutePath();
//            String sdpath = rootPath+File.separator+"adfire"+File.separator+"cmd"+File.separator;
//            File vcmdFile = new File(sdpath );
//
//            if(vcmdFile.exists()){
//
//                File [] files = vcmdFile.listFiles();
//                for(int i=0;i<files.length;i++){
//                    Log.d(TAG, files[i].getName());
//                    if(files[i].getName().indexOf('2') > -1){
//                        currentFile = files[i].getAbsolutePath();
//                        break;
//                    }
//                }
//                if(MediaFileUtil.isVideoFileType(currentFile)){
//                    TimeStamp = -1;
//                    playVideo(currentFile);;
//                }else{
//                    findViewById(R.id.player_image).setLayoutParams(new LinearLayout.LayoutParams(LinearLayoutCompat.LayoutParams.MATCH_PARENT, LinearLayoutCompat.LayoutParams.MATCH_PARENT, 0));
//                    Bitmap bmpDefaultPic;
//
//
//                    bmpDefaultPic = BitmapFactory.decodeFile(currentFile,null);
//                    playImage.setImageBitmap(bmpDefaultPic);
//                    TimeStamp = CmdTime;
//                    isCmd = true;
//                }
//            }
        }
        catch (Exception e){

        }

    }
    private void EventMessageFor3(){
        try{
            isCmd = 3;
            if(MediaFileUtil.isVideoFileType(currentFile)){
                player.stop();
            }
            playlist = cmd1list;
            current = 0;
            playCurrent();

//            String rootPath =Environment.getExternalStorageDirectory().getAbsolutePath();
//            String sdpath = rootPath+File.separator+"adfire"+File.separator+"cmd"+File.separator;
//            File vcmdFile = new File(sdpath );
//
//            if(vcmdFile.exists()){
//
//                File [] files = vcmdFile.listFiles();
//                for(int i=0;i<files.length;i++){
//                    Log.d(TAG, files[i].getName());
//                    if(files[i].getName().indexOf('2') > -1){
//                        currentFile = files[i].getAbsolutePath();
//                        break;
//                    }
//                }
//                if(MediaFileUtil.isVideoFileType(currentFile)){
//                    TimeStamp = -1;
//                    playVideo(currentFile);;
//                }else{
//                    findViewById(R.id.player_image).setLayoutParams(new LinearLayout.LayoutParams(LinearLayoutCompat.LayoutParams.MATCH_PARENT, LinearLayoutCompat.LayoutParams.MATCH_PARENT, 0));
//                    Bitmap bmpDefaultPic;
//
//
//                    bmpDefaultPic = BitmapFactory.decodeFile(currentFile,null);
//                    playImage.setImageBitmap(bmpDefaultPic);
//                    TimeStamp = CmdTime;
//                    isCmd = true;
//                }
//            }
        }
        catch (Exception e){

        }
    }
    private void EventMessageForCmd(String cmd){
        try{
            if(MediaFileUtil.isVideoFileType(currentFile)){
                player.stop();
            }
            if(cmd.equals("1")){
                EventMessageFor1();

            }else if(cmd.equals("2")){
                EventMessageFor2();
            }else{
                EventMessageFor3();
            }
//            String rootPath =Environment.getExternalStorageDirectory().getAbsolutePath();
//            String sdpath = rootPath+File.separator+"adfire"+File.separator+"cmd"+File.separator;
//            File vcmdFile = new File(sdpath );
//
//            if(vcmdFile.exists()){
//
//                File [] files = vcmdFile.listFiles();
//                for(int i=0;i<files.length;i++){
//                    Log.d(TAG, files[i].getName());
//                    if(files[i].getName().indexOf(cmd) > -1){
//                        currentFile = files[i].getAbsolutePath();
//                        break;
//                    }
//                }
//                if(MediaFileUtil.isVideoFileType(currentFile)){
//                    TimeStamp = -1;
//                    playVideo(currentFile);;
//                }else{
//                    findViewById(R.id.player_image).setLayoutParams(new LinearLayout.LayoutParams(LinearLayoutCompat.LayoutParams.MATCH_PARENT, LinearLayoutCompat.LayoutParams.MATCH_PARENT, 0));
//                    Bitmap bmpDefaultPic;
//
//
//                    bmpDefaultPic = BitmapFactory.decodeFile(currentFile,null);
//                    playImage.setImageBitmap(bmpDefaultPic);
//                    TimeStamp = CmdTime;
//                    isCmd = true;
//
//                }
//            }
        }
        catch (Exception e){

        }

    }
    private void EventMessageForReset(){
        try{
            findViewById(R.id.player_image).setLayoutParams(new LinearLayout.LayoutParams(LinearLayoutCompat.LayoutParams.MATCH_PARENT, LinearLayoutCompat.LayoutParams.MATCH_PARENT, 1));

        }
        catch (Exception e){

        }

    }

    private void EventMessageForPing(){
        try{


            if(tcpServerTread.sendPing("{\"cmd\":\"play_0\"}") == true){
                tick_send ++;
            }
            if(tick_send - tick_recv > 3){
                tcpServerTread.closeClient();
                tick_send = 0;
                tick_recv = 0;
            }
        }
        catch (Exception e){

        }

    }
    private void EventMeessageForPlay(){
        PlayNext();
    }
    private void PlayNext(){
        current = current + 1;
        if(playlist.size() <= current){
            current = 0;
            if(isCmd != 0){
                isCmd = 0;
                playlist = videolist;
            }
        }
        playCurrent();
    }
    private void playCurrent(){
        currentFile = playlist.get(current);
        //Toast.makeText(FullscreenActivity.this,currentFile,Toast.LENGTH_LONG);
        Log.d(TAG, "playCurrent: "+currentFile);
        if(MediaFileUtil.isVideoFileType(currentFile)){
            playVideo(currentFile);
        }else{
            playImage(currentFile, current);
        }
    }

    private void createWorkDir(){
        try{
            String rootPath =Environment.getExternalStorageDirectory().getAbsolutePath();
            String workDir = rootPath+File.separator+"adfire";
            String cmd1Dir = rootPath+File.separator+"adfire"+File.separator+"cmd1";
            String cmd2Dir = rootPath+File.separator+"adfire"+File.separator+"cmd2";
            String cmd3Dir = rootPath+File.separator+"adfire"+File.separator+"cmd3";
            String adDir = rootPath+File.separator+"adfire"+File.separator+"ad";
            File workFile = new File(workDir);
            if(workFile.getParentFile().exists()){
                if(!workFile.exists())
                    workFile.mkdir();
            }
            File cmd1File = new File(cmd1Dir);
            if(cmd1File.getParentFile().exists()){
                if(!cmd1File.exists())
                    cmd1File.mkdir();
            }
            File cmd2File = new File(cmd2Dir);
            if(cmd2File.getParentFile().exists()){
                if(!cmd2File.exists())
                    cmd2File.mkdir();
            }
            File cmd3File = new File(cmd3Dir);
            if(cmd3File.getParentFile().exists()){
                if(!cmd3File.exists())
                    cmd3File.mkdir();
            }

            File adFile = new File(adDir);
            if(adFile.getParentFile().exists()){
                if(!adFile.exists())
                    adFile.mkdir();
            }
        }catch (Exception e){

        }
    }
    @Subscribe(threadMode = ThreadMode.MAIN,priority = 100,sticky = false)     //在UI线程执行，100  为优先级
    public void onEvent(Message message){
        //LogUtil.getInstance().info(OtherUtil.getCurrentTime()+"接收指令:"+ message.what);
        switch(message.what){

            case 0x11:
                EventMeessageForPlay();
                break;


            case 0x21://1命令按钮
                EventMessageForReply();
                Log.d(TAG, "=========== 0x21 ===========");
                EventMessageForCmd("1");
                break;
            case 0x22://2命令按钮
                Log.d(TAG, "=========== 0x22 ===========");
                EventMessageForReply();
                EventMessageForCmd("2");
                break;
            case 0x23://2命令按钮
                EventMessageForReply();
                Log.d(TAG, "=========== 0x23 ===========");
                EventMessageForCmd("3");
                break;
            case 0x20://2ping
                tick_recv ++;
                Log.d(TAG, "=========== 0x20 ===========");

                break;


        }
        ;
    }


}
